var express = require('express');
var router = express.Router();

var data=[
  	{name:"小白",age:1231,guoji:"韩国",techang:"剑术"},
  	{name:"小杜",age:1212,guoji:"中国",techang:"吃肉"},
  	{name:"小牧",age:1123,guoji:"中国",techang:"像竹子"},
  	{name:"毛爷爷",age:134,guoji:"中国",techang:"吃肉"},
  ];

/* GET users listing. */
router.get('/', function(req, res, next) {
	var content=`
		<h1>鹅鹅鹅</h1>
		<p>
			落霞与孤鹜齐飞,
			秋水共长天一色
		</p>
	`;
  res.send(content);
});

router.get('/shirens', function(req, res, next) {
  

  res.render('shirens',{data:data});
});
//shirenupdate/小白/
router.get('/shirenupdate/:userName',
 function(req, res, next) {
  
  var sr=data.filter((item)=>{
    return item.name==req.params.userName;
  })[0];
  // res.send(sr.age+"");
  res.render('shirenupdate',{aaa:sr});
});

router.get('/addShiRen',
 function(req, res, next) {
  
  res.render('addShiRen',null);
});
//删除诗人
router.get('/shirendelete/:userName',
 function(req, res, next) {
 	 data.forEach((item,index,arr)=>{
    if(item.name==req.params.userName){
      arr.splice(index,1);
    }
  });
  res.redirect('/wenxue/shirens');//重定向
});
//更新诗人
router.post('/shirenupdateInfo',
 function(req, res, next) {
  data.forEach((item)=>{
    if(item.name==req.body.name){
      item.age=req.body.age;
      item.guoji=req.body.guoji;
      item.techang=req.body.techang;
    }
  });
  res.send(req.body);
});

router.post('/shirenupAddInfo',
 function(req, res, next) {
 	if(req.body.name){
    data.push({
      name:req.body.name,
      age:req.body.age,
      guoji:req.body.guoji,
      techang:req.body.techang
    });
  }
  
  if(Math.random()>0.5){
    res.send("success");
  }else{
    res.send("fail");
  }
});

module.exports = router;
